/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package orderProcessingProcess.dataStorage;

import java.util.HashMap;
import java.util.Map;
import orderProcessingProcess.model.Customer;
import orderProcessingProcess.util.AIC_log;

/**
 *
 * @author dreni
 */
public class DataBackend {
	
	//Singeltone (thread-safe) DataBackend object
    private static DataBackend instance = new DataBackend();

    //Map used to store <customer_id, Customer>
    private Map<String, Customer> customers = new HashMap<String, Customer>();;
    
   
    private DataBackend(){
    }
    
    public static DataBackend getInstance(){
    	return instance;
    }

    //Search for a Customer
    public Customer getCustomer(Customer c){
        if(c == null || c.getId()== null || "".equals(c.getId()) ){
            return null;
        } else {
            return this.getCustomerById(c.getId());
        }
    }

    // Search for a Customer by ID
    public Customer getCustomerById(String customerId){
        if(customers.containsKey(customerId)){
            return customers.get(customerId);
        }else
            return null;
    }
	
    public synchronized boolean addCustomer(Customer c){
        if(c== null){
            return false;
        }
        if(c.getId() == null){
            c.setId("" + customers.size() + 1);
        }
        customers.put(c.getId(), c);
        AIC_log.print("DataBackend", "Added customer with ID "+ c.getId());
        return true;
    }

    public synchronized boolean updateCustomer(Customer c){
        if(customers.containsKey(c.getId())){
            customers.remove(c.getId());
            customers.put(c.getId(), c);
            AIC_log.print("DataBackend", "Updated customer with ID "+ c.getId());
            return true;
        }else
            return false;

    }

    public synchronized boolean deleteCustomer(Customer c){
        if(c != null){
            customers.remove(c.getId());
            AIC_log.print("DataBackend", "Deleted customer with ID "+ c.getId());
            return true;
        }
        return false;
    }
    
    public synchronized boolean deleteCustomerById(String customerId){
    	if(customers.remove(customerId) != null) {
            AIC_log.print("DataBackend", "Deleted customer with ID "+ customerId);
            return true;
        }
        return false;
    }
    
    public synchronized void deleteAllCustomer(){
        customers.clear();
    }  
}
